
package com.probiz.estore.core.filter;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.web.filter.OncePerRequestFilter;

import com.opensymphony.clickstream.Clickstream;
import com.probiz.estore.common.helper.ConfigUtil;
import com.probiz.estore.core.util.ContextUtil;

/**
 * Record user click/request actions. These data can be used to generate some
 * useful reports, or trace user actions. Also, can be used to save views and
 * return to last n view. Note, posted requests are not saved, audit is a more
 * suitable place for some purpose.
 */
public class ClickStreamFilter extends OncePerRequestFilter {

	final static String[]	filterUrls	= new String[] { "postLogin.html" };

	final static String[]	filterWords	= new String[] { "decorator",
			"selecter", "printable"	};

	ServletContext			context;

	boolean					isFront;

	@Override
	public void doFilterInternal(HttpServletRequest request,
			HttpServletResponse response, FilterChain chain)
			throws IOException, ServletException {

		chain.doFilter(request, response);

		if ((ConfigUtil.getInstance().getIsRecentViewEnabled() || !isFront)
				&& request.getMethod().equalsIgnoreCase("GET")
				&& !hasFilteredWord(request.getQueryString())
				&& !hasFilteredUrl(request.getRequestURI())) {
			HttpSession session = request.getSession(false);
			if (session != null) {
				Clickstream clickstream = (Clickstream) session
						.getAttribute(Clickstream.USER_CLICKSTREAM);
				if (clickstream == null) {
					clickstream = new Clickstream();
					session.setAttribute(Clickstream.USER_CLICKSTREAM,
							clickstream);
				}
				clickstream.addRequest(request);
			}
		}
	}

	protected boolean hasFilteredUrl(String uri) {
		if (uri != null) {
			for (int i = 0; i < filterUrls.length; i++) {
				if (uri.indexOf(filterUrls[i]) >= 0) {
					return true;
				}
			}
		}

		return false;
	}

	protected boolean hasFilteredWord(String queryString) {
		if (queryString != null) {
			for (int i = 0; i < filterWords.length; i++) {
				if (queryString.indexOf(filterWords[i]) >= 0) {
					return true;
				}
			}
		}

		return false;
	}

	@Override
	protected void initFilterBean() throws ServletException {
		this.isFront = ContextUtil.isFront();
		context = getServletContext();
	}
}
